package leetcode.mthread.交替打印FooBar;

import java.util.concurrent.Semaphore;

/**
 * 信号量实现
 *
 * @author scylla
 * @version V1.0
 * @project echo-java-base
 * @title
 * @package leetcode.mthread.交替打印FooBar
 * @since 2021/12/7 1:34 下午
 */
public class FooBarSemaphore {

    private final Semaphore foos = new Semaphore(1);
    private final Semaphore bars = new Semaphore(0);

    private int n;

    public FooBarSemaphore(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            foos.acquire();
            // printFoo.run() outputs "foo". Do not change or remove this line.
            printFoo.run();
            bars.release();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            bars.acquire();
            // printBar.run() outputs "bar". Do not change or remove this line.
            printBar.run();
            foos.release();
        }
    }
}
